<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useResizeObserver } from '@vueuse/core';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({}),
  },
});

const chartRef = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;

const getBubbleData = () => {
  const units = props.chartData.units || [];
  const activeData = props.chartData.activeData || [];
  const memberData = props.chartData.memberData || [];
  const data: {name: string, type: string, value: [number, number]}[] = [];
  for (let i = 0; i < units.length; i++) {
    data.push({
      name: units[i],
      type: '激活人数',
      value: [i, activeData[i] ?? 0],
    });
    data.push({
      name: units[i],
      type: '会员人数',
      value: [i, memberData[i] ?? 0],
    });
  }
  return data;
};

const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(
    chartRef?.value.querySelector('#horizontalChart') as HTMLElement,
  );

  const units = props.chartData.units || [];
  const maxValue = Math.max(
    ...(props.chartData.activeData || []),
    ...(props.chartData.memberData || []),
    10
  );

  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      formatter: (params: any) => {
        let unit = params.data.name ?? '';
        if (unit.length > 14) {
          unit = unit.slice(0, 7) + '...' + unit.slice(-5);
        }
        return `${unit}<br/>${params.data.type}: ${params.data.value[1]}`;
      },
    },
    grid: {
      top: '5%',
      left: '2%',
      right: '4%',
      bottom: '18%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: units.map((_: any, idx: any) => idx),
      axisLabel: { show: false },
      axisLine: { show: false }, // 不显示x轴线
      splitLine: { show: false },
      axisTick: { show: false },
    },
    yAxis: {
      type: 'value',
      name: '',
      nameTextStyle: { color: '#fff', fontSize: 14, padding: [0, 0, 8, 0] },
      axisLabel: { show: false }, // 不显示y轴刻度
      axisLine: { show: false },  // 不显示y轴线
      splitLine: { show: false }, // 不显示横线
      axisTick: { show: false },  // 不显示刻度线
    },
    legend: {
      data: ['激活人数', '会员人数'],
      textStyle: { color: '#fff' },
      top: 0,
      right: 10,
    },
    series: [
      {
        name: '激活人数',
        type: 'scatter',
        data: getBubbleData().filter(d => d.type === '激活人数'),
        symbolSize: function (val: any) {
          return Math.max(8, Math.min(40, (val[1] / maxValue) * 40));
        },
        itemStyle: {
          color: new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
            { offset: 0, color: '#FFB3B3' },
            { offset: 1, color: '#FF3B3B' },
          ]),
          opacity: 0.8,
        },
        emphasis: {
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2,
          },
        },
        label: { show: false },
      },
      {
        name: '会员人数',
        type: 'scatter',
        data: getBubbleData().filter(d => d.type === '会员人数'),
        symbolSize: function (val: any) {
          return Math.max(8, Math.min(40, (val[1] / maxValue) * 40));
        },
        itemStyle: {
          color: new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
            { offset: 0, color: '#B3E5FF' },
            { offset: 1, color: '#0086FF' },
          ]),
          opacity: 0.8,
        },
        emphasis: {
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2,
          },
        },
        label: { show: false },
      },
    ],
  };

  chart.setOption(option);
};

watch(
  () => props.chartData,
  () => {
    initChart();
  },
  { deep: true },
);

useResizeObserver(chartRef, () => {
  chart?.resize();
});

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  chart?.dispose();
});
</script>

<template>
  <div class="chart-container" ref="chartRef">
    <div class="chart" id="horizontalChart"></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.chart {
  width: 100%;
  height: 100%;
  padding: 12px;
}
</style>